package com.zhongyewx.teachercert.utils;

import android.os.Environment;
import android.text.TextUtils;

import java.io.File;

public class ZYSDCardUtils {
    private static final String TAG = "ZYSDCardUtils";

    public static boolean isExternalStorageWriteable() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
    public static String getExternalStoragePath() {
        if (isExternalStorageWriteable()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            ZYLog.warn(TAG, "external storage is not writeable!");
            return null;
        }
    }
    public static boolean checkDirectory(String dir) {
        if (dir == null || dir.isEmpty()) {
            return false;
        }

        if (!isExternalStorageWriteable()) {
            return false;
        }

        File f = new File(dir);
        if (!f.exists()) {
            String[] pathSeg = dir.split(File.separator);
            StringBuilder path = new StringBuilder();
            for (String temp : pathSeg) {
                if (TextUtils.isEmpty(temp)) {
                    path.append(File.separator);
                    continue;
                } else {
                    path.append(temp).append(File.separator);
                }
                File tempPath = new File(path.toString());
                if (tempPath.exists() && !tempPath.isDirectory()) {
                    tempPath.delete();
                }
                tempPath.mkdirs();
            }
        } else {
            if (!f.isDirectory()) {
                f.delete();
                f.mkdirs();
            }
        }
        return true;
    }
}
